<script lang="ts">
import { defineComponent } from "vue";
import BlameView from "./BlameView.vue";
import { ElMessageBox } from "element-plus";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {
    BlameView,
  },
});
</script>
<script lang="ts" setup>
import { useRouter } from "vue-router";
import { reactive, ref, onMounted, getCurrentInstance, toRefs } from "vue";

const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties;
const form: { [key: string]: any } = reactive({
  owning_user_id: "",
  owning_user_name: "",
  uid: "",
  object_name: "",
  model_code: "",
  factory: "",
  send_dest: "",
  product_level: "",
  dr_type: "",
  dr_type_other: "",
  impl_date: "",
  attendance: "",
  is_meeting_valid: true,
});

const blameForms: { [key: string]: any } = reactive({});

//const uid = ref("");
const owningUserId = ref("");
const userId = ref("");
const hasSaveButton = ref(false);
const formReadOnly = ref(false);
const router = useRouter();
const blameSubject = ref("");
const activeNames = ref(["1"]);
const saving = ref(false);
const handleChange = (val: string[]) => {
  console.log(val);
};
const onSubmit = () => {
  console.log("submit!");
};

// 将 JSON 字符串转换为 form 对象
const jsonToForm = (jsonData: { [key: string]: any }) => {
  for (const key in jsonData) {
    if (Object.prototype.hasOwnProperty.call(jsonData, key)) {
      const value = jsonData[key];
      console.log(`${key}: ${value}`);
      if (Object.prototype.hasOwnProperty.call(form, key)) {
        form[key] = jsonData[key];
      }
    }
  }
};

onMounted(() => {
  let uid = router.currentRoute.value.query.uid as string;
  let isReadOnlyStr = router.currentRoute.value.query.isReadOnly as string;
  let saveButton = router.currentRoute.value.query.saveButton as string;
  owningUserId.value = router.currentRoute.value.query.owningUserId as string;
  userId.value = router.currentRoute.value.query.userId as string;
  hasSaveButton.value = saveButton && saveButton == "true" ? true : false;
  console.log("uid = " + uid);
  setFormReadOnly(isReadOnlyStr == "true");
  form.uid = uid;
  if (uid) {
    loadData();
  }
  // alert("Component mounted");
  // 在这里可以执行一些初始化操作
  (window as any).submitForm = submitForm;
  (window as any).setFormReadOnly = setFormReadOnly;
});
let tabIndex = 0;
const editableTabsValue = ref("");
const editableTabs = ref([
  {
    title: "",
    name: "",
    content: "",
    data: {},
  },
  // {
  //   title: "Tab 1",
  //   name: "1",
  //   content: "Tab 1 content",
  //   data: {},
  // },
  // {
  //   title: "Tab 2",
  //   name: "2",
  //   content: "Tab 2 content",
  //   data: {},
  // },
]);

const initEditableTabData = () => {
  editableTabs.value = [];
  for (const subject in blameForms) {
    const blameFormData = blameForms[subject];
    editableTabs.value.push({
      title: blameFormData.subject,
      name: blameFormData.subject,
      content: "",
      data: blameFormData,
    });
    if (editableTabsValue.value.length == 0) {
      editableTabsValue.value = blameFormData.subject;
    }
  }
};

const loadData = () => {
  $http
    .get("/getDelrData?uid=" + form.uid)
    .then((response: { data: any }) => {
      console.log("评审单查询结果", response.data);
      jsonToForm(response.data);
    })
    .catch((error: any) => {
      console.log(error);
    });

  $http
    .get("/getBlames?uid=" + form.uid + "&userId=" + userId.value)
    .then((response: { data: [] }) => {
      console.log("指摘查询结果", response.data);
      response.data.forEach((element: any) => {
        //console.log("处理数据：" + element);
        const json = JSON.parse(element);
        //console.log("处理数据>> " + json.subject);
        setBlameFormData(json.subject, json);
        initEditableTabData();
      });
    })
    .catch((error: any) => {
      console.log(error);
    });

  if (owningUserId.value) {
    form.owning_user_id = owningUserId.value;
    $http
      .get("/getUserNameById?userId=" + owningUserId.value)
      .then((response: { data: any }) => {
        console.log("查询结果", response.data);
        form.owning_user_name = response.data + " (" + owningUserId.value + ")";
      });
  }
};

const submitForm = () => {
  console.log("Form submitted from JxBrowser!");
  // 模拟表单提交操作
  //alert("Form submitted from JxBrowser!");
  form.object_name = "XXXXXXXXXXXXX";
  onSubmit();
};

const setFormReadOnly = (isReadOnly: boolean) => {
  formReadOnly.value = isReadOnly;
};

//给BlameView调用的
const setBlameFormData = (subject: string, formData: any) => {
  //console.log("接收到子页数据：", formData);
  blameForms[subject] = formData;
  //TODO11
};

const saveData = async () => {
  saving.value = true;
  try {
    const saveDesignEvalImplUrl = "/saveDelrData";
    const saveBlamesUrl = "/saveBlames";
    console.log("保存主表单数据：", form);
    const response1 = await $http.post(saveDesignEvalImplUrl, form);
    console.log("提交结果", response1.data);
    const data = {
      puid: form.uid,
      userId: userId.value,
      blames: blameForms,
    };
    console.log("保存指摘表单数据：", data);
    const response2 = await $http.post(saveBlamesUrl, data);
    console.log("提交结果", response2.data);
    ElMessage({
      type: "success",
      message: "保存成功",
    });
  } catch (error) {
    console.log(error);
    ElMessage({
      type: "error",
      message: error,
    });
  }
  saving.value = false;
};

// const unicodeToString = (unicodeStr: string) => {
//   return unicodeStr.replace(/\\u[\dA-F]{4}/gi, function (match) {
//     return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
//   });
// };

const addTab = (targetName: string) => {
  ElMessageBox.prompt("请输入指摘主题", "输入", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    inputValidator: (inputValue: any) => {
      if (!inputValue) {
        return "主题不得为空";
      }
      const existingNames = editableTabs.value.map((tab) => tab.name);
      if (existingNames.includes(inputValue)) {
        return "该主题已存在，请输入不同的主题";
      }
      return true;
    },
  })
    .then(({ value }) => {
      // ElMessage({
      //   type: "success",
      //   message: `Your email is:${value}`,
      // });
      editableTabs.value.push({
        title: value,
        name: value,
        content: "",
        data: {
          design_eval_impl_uid: form.uid,
        },
      });
      editableTabsValue.value = value;
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Input canceled",
      });
    });

  // const subject = blameSubject.value;
  // const newTabName = `${++tabIndex}`;
  // editableTabs.value.push({
  //   title: "New Tab",
  //   name: newTabName,
  //   content: "New Tab content",
  // });
  // editableTabsValue.value = newTabName;
};
const removeTab = (targetName: string) => {
  const tabs = editableTabs.value;
  let activeName = editableTabsValue.value;
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          activeName = nextTab.name;
        }
      }
    });
  }

  editableTabsValue.value = activeName;
  editableTabs.value = tabs.filter((tab) => tab.name !== targetName);
};
</script>
<template>
  <div>
    <div class="fixed-button" v-if="hasSaveButton">
      <el-button
        type="primary"
        @click="saveData"
        :loading="saving"
        :disabled="saving"
        >保存</el-button
      >
    </div>
    <el-form
      :model="form"
      :disabled="formReadOnly"
      :style="{ marginTop: hasSaveButton ? '70px' : '10px' }"
      label-width="auto"
      label-position="left"
      style="max-width: 600px"
      class="form-content"
    >
      <el-form-item label="作成者">
        <el-input v-model="form.owning_user_name" prefix-icon="User" readonly />
      </el-form-item>
      <el-form-item label="品名">
        <el-input v-model="form.object_name" />
      </el-form-item>
      <el-form-item label="型号">
        <el-input v-model="form.model_code" />
      </el-form-item>
      <el-form-item label="工厂">
        <el-radio-group v-model="form.factory">
          <el-radio label="GD" value="GD" name="factory"></el-radio>
          <el-radio label="海外" value="海外" name="factory"></el-radio>
          <el-radio label="其它" value="其它" name="factory"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="发送地">
        <el-radio-group v-model="form.send_dest">
          <el-radio label="国内" value="国内" name="send_dest"></el-radio>
          <el-radio label="出口" value="出口" name="send_dest"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="产品等级">
        <el-radio-group v-model="form.product_level">
          <el-radio label="A" value="A" name="product_level"></el-radio>
          <el-radio label="B" value="B" name="product_level"></el-radio>
          <el-radio label="C" value="C" name="product_level"></el-radio>
          <el-radio label="D" value="D" name="product_level"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="DR的种类">
        <el-radio-group v-model="form.dr_type">
          <el-radio
            label="DR0 (包括但不限于：D-FMEA、控制软件检讨、控制硬件检讨等)"
            value="DR0"
            name="dr_type"
          ></el-radio>
          <el-radio
            label="DR1 (包括但不限于：D-FMEA、P-FMEA、风险评价、设计品质确认、图面检讨、三方确认会等)"
            value="DR1"
            name="dr_type"
          ></el-radio>
          <el-radio
            label="DR2 (包括但不限于：D-FMEA、P-FMEA、风险评价、设计品质确认、图面检讨、三方确认会等)"
            value="DR2"
            name="producdr_typetLevel"
          ></el-radio>
          <el-radio label="其他" value="other" name="dr_type"></el-radio>
        </el-radio-group>
        <el-input
          v-model="form.dr_type_other"
          :disabled="form.dr_type != '其他'"
        />
      </el-form-item>
      <el-form-item label="实施日期">
        <el-date-picker
          v-model="form.impl_date"
          type="date"
          placeholder="请选择日期"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="DR有效性">
        <el-col :span="3" class="text-center">
          <span class="text-gray-500"> 出席率</span>
        </el-col>
        <el-col :span="6">
          <el-input v-model="form.attendance">
            <template v-slot:append>%</template>
          </el-input>
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500"></span>
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500"> 会议</span>
        </el-col>
        <el-col :span="7">
          <el-radio-group v-model="form.is_meeting_valid">
            <el-switch
              v-model="form.is_meeting_valid"
              inline-prompt
              class="ml-2"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              active-text="有效"
              inactive-text="无效"
            />
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label="指摘数">
        <el-row>
          <el-col :span="7" class="text-left">
            <span> ×件数: </span>
          </el-col>
          <el-col :span="15">
            <el-input v-model="form.attendance">
              <template v-slot:append>系统自动计算</template>
            </el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7" class="text-left">
            <span> △件数: </span>
          </el-col>
          <el-col :span="15">
            <el-input v-model="form.attendance">
              <template v-slot:append>系统自动计算</template>
            </el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7" class="text-left">
            <span> ○件数: </span>
          </el-col>
          <el-col :span="15">
            <el-input v-model="form.attendance">
              <template v-slot:append>系统自动计算</template>
            </el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7" class="text-left">
            <span> 确认件数: </span>
          </el-col>
          <el-col :span="15">
            <el-input v-model="form.attendance">
              <template v-slot:append>系统自动计算</template>
            </el-input>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 20px">
      <el-button
        size="primary"
        :disabled="formReadOnly"
        @click="addTab(editableTabsValue)"
      >
        新建指摘
      </el-button>
      <!-- <el-input
        v-model="blameSubject"
        style="max-width: 600px"
        placeholder="请输入主题以新增指摘"
      >
        <template #append>
          <el-button icon="Plus" @click="addTab(editableTabsValue)" />
        </template>
      </el-input> -->
    </div>
    <el-tabs
      v-model="editableTabsValue"
      type="card"
      class="demo-tabs"
      :closable="!formReadOnly"
      @tab-remove="removeTab"
    >
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >
        <BlameView
          :userId="userId"
          :subject="item.name"
          :formReadOnly="formReadOnly"
          :formData="item.data"
          @setBlameFormData="setBlameFormData"
        ></BlameView>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style>
.text-left {
  text-align: left;
  width: 15px;
}
.fixed-button {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 999;
}
.form-content {
  /* 确保表单内容不被保存按钮遮挡 */
  /* margin-top: 70px; */
  margin-top: 10px;
}
</style>
